/**
 * 最简化的位置选择工具
 * 直接使用微信原生API，避免复杂的权限检查
 */

export interface LocationData {
  name: string;
  address: string;
  latitude: number;
  longitude: number;
}

/**
 * 简单的位置选择器
 */
export const LocationSelector = {
  
  /**
   * 选择位置（直接调用微信API）
   */
  chooseLocation(currentLocation?: LocationData): Promise<LocationData> {
    return new Promise((resolve, reject) => {
      const options: any = {
        success: (res: any) => {
          console.log('位置选择成功:', res);
          
          const location: LocationData = {
            name: res.name || '',
            address: res.address || '',
            latitude: res.latitude,
            longitude: res.longitude
          };
          
          // 显示确认对话框
          wx.showModal({
            title: '确认地址',
            content: `${location.address}\n${location.name}`,
            confirmText: '确认',
            cancelText: '重新选择',
            success: (modalRes) => {
              if (modalRes.confirm) {
                resolve(location);
              } else {
                // 重新选择
                this.chooseLocation(currentLocation).then(resolve).catch(reject);
              }
            }
          });
        },
        fail: (err: any) => {
          console.error('选择位置失败:', err);
          
          if (err.errMsg.includes('cancel')) {
            // 用户取消，静默处理
            return;
          } else if (err.errMsg.includes('auth') || err.errMsg.includes('deny')) {
            wx.showModal({
              title: '需要位置权限',
              content: '请在手机设置中开启微信的位置权限，然后重新尝试',
              showCancel: false,
              confirmText: '知道了'
            });
          } else {
            wx.showToast({
              title: '选择位置失败',
              icon: 'none'
            });
          }
          reject(err);
        }
      };

      // 设置初始位置
      if (currentLocation?.latitude && currentLocation?.longitude) {
        options.latitude = currentLocation.latitude;
        options.longitude = currentLocation.longitude;
      }

      wx.chooseLocation(options);
    });
  },

  /**
   * 获取当前位置
   */
  getCurrentLocation(): Promise<LocationData> {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        success: (res) => {
          console.log('获取当前位置成功:', res);
          
          const location: LocationData = {
            name: '当前位置',
            address: `纬度:${res.latitude.toFixed(6)}, 经度:${res.longitude.toFixed(6)}`,
            latitude: res.latitude,
            longitude: res.longitude
          };
          
          resolve(location);
        },
        fail: (err) => {
          console.error('获取当前位置失败:', err);
          
          if (err.errMsg.includes('auth') || err.errMsg.includes('deny')) {
            wx.showModal({
              title: '需要位置权限',
              content: '请在手机设置中开启微信的位置权限，然后重新尝试',
              showCancel: false,
              confirmText: '知道了'
            });
          } else {
            wx.showToast({
              title: '获取位置失败，请检查GPS是否开启',
              icon: 'none'
            });
          }
          reject(err);
        }
      });
    });
  },

  /**
   * 打开地图查看位置
   */
  openLocation(location: LocationData): Promise<void> {
    return new Promise((resolve, reject) => {
      wx.openLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        name: location.name,
        address: location.address,
        scale: 16,
        success: () => {
          resolve();
        },
        fail: (err) => {
          console.error('打开地图失败:', err);
          wx.showToast({
            title: '打开地图失败',
            icon: 'none'
          });
          reject(err);
        }
      });
    });
  }
};

// 兼容导出
module.exports = {
  LocationSelector,
  SimpleLocationHelper: LocationSelector,
  LocationHelper: LocationSelector,
  MapSelector: {
    chooseLocationWithConfirm: LocationSelector.chooseLocation.bind(LocationSelector),
    smartChooseLocation: LocationSelector.chooseLocation.bind(LocationSelector)
  }
};


